#!/bin/bash -e

TOP_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )"
ARTIFACTS_DIR="${TOP_DIR}/dist/artifacts"
SCRIPTS_DIR="${TOP_DIR}/scripts"
PACKAGE_HARVESTER_OS_DIR="${TOP_DIR}/package/harvester-os"
BUNDLE_DIR="${PACKAGE_HARVESTER_OS_DIR}/iso/bundle"

mkdir -p ${ARTIFACTS_DIR}

source ${SCRIPTS_DIR}/version
source ${SCRIPTS_DIR}/version-rke2
source ${SCRIPTS_DIR}/version-rancher
source ${SCRIPTS_DIR}/version-harvester ${TOP_DIR}/../harvester
source ${SCRIPTS_DIR}/version-monitoring

BASE_OS_IMAGE="rancher/harvester-os:20220308"
HARVESTER_OS_IMAGE=rancher/harvester-os:$VERSION

cd ${PACKAGE_HARVESTER_OS_DIR}

PRETTY_NAME="Harvester ${VERSION}"

cat > harvester-release.yaml <<EOF
harvester: ${HARVESTER_VERSION}
harvesterChart: ${HARVESTER_CHART_VERSION}
os: ${PRETTY_NAME}
kubernetes: ${RKE2_VERSION}
rancher: ${RANCHER_VERSION}
monitoringChart: ${MONITORING_VERSION}
EOF

docker build --pull \
	--build-arg BASE_OS_IMAGE="${BASE_OS_IMAGE}" \
	--build-arg HARVESTER_PRETTY_NAME="${PRETTY_NAME}" \
	-t ${HARVESTER_OS_IMAGE} .

PROJECT_PREFIX="harvester"
if [ -n "$VERSION" ];
then
  PROJECT_PREFIX+="-${VERSION}"
else
  PROJECT_PREFIX+="-master"
fi

# Copy kernel, initrd out for PXE boot
KERNEL=$(docker run --rm ${HARVESTER_OS_IMAGE} readlink /boot/vmlinuz)
INITRD=$(docker run --rm ${HARVESTER_OS_IMAGE} readlink /boot/initrd)
docker create --cidfile=os-img-container ${HARVESTER_OS_IMAGE}
docker cp $(<os-img-container):/boot/${KERNEL} ${ARTIFACTS_DIR}/${PROJECT_PREFIX}-vmlinuz-${ARCH}
docker cp $(<os-img-container):/boot/${INITRD} ${ARTIFACTS_DIR}/${PROJECT_PREFIX}-initrd-${ARCH}
chmod +r ${ARTIFACTS_DIR}/${PROJECT_PREFIX}-initrd-${ARCH}
docker rm $(<os-img-container) && rm -f os-img-container

# Make sure files under bundle dir can be read by nginx
find $BUNDLE_DIR -type f -exec chmod +r {} +

# build ISO
ISO_PREFIX="${PROJECT_PREFIX}-${ARCH}"
cp harvester-release.yaml iso
yq e ".overlay.isoimage = \"$(pwd)/iso\"" iso.yaml -i
echo "set harvester_version=${VERSION}" > iso/boot/grub2/harvester.cfg
luet-makeiso iso.yaml --image "${HARVESTER_OS_IMAGE}" --output ${ARTIFACTS_DIR}/${ISO_PREFIX}
rm ${ARTIFACTS_DIR}/${ISO_PREFIX}.iso.sha256

# Extract the squashfs image for PXE boot
xorriso -osirrox on -indev ${ARTIFACTS_DIR}/${ISO_PREFIX}.iso -extract /rootfs.squashfs ${ARTIFACTS_DIR}/${PROJECT_PREFIX}-rootfs-${ARCH}.squashfs

# Write checksum
cd ${ARTIFACTS_DIR}
CHECKSUM_FILE=${ISO_PREFIX}.sha512
sha512sum ${PROJECT_PREFIX}* > $CHECKSUM_FILE
